<?php

/**
 * Server_Api_Dynamic
 * 验证码服务
 * Author: netman
 * DateTime:  2023/9/11 16:37
 */
class Service_Api_Dynamic
{

    use Trait_Api_Common;
    use Trait_Api_Image;

    public function __construct()
    {

    }

    public function code($params) : array
    {

        $user = Arr::get($params, 'receiver');
        $messageType = Arr::get($params, 'msgtype');
        $prefix = "{$messageType}_send";
        $data = array();

        try {

            $code = rand(1000, 9999);
            $send_time_key = 'quick_login_send_time' . $user;
            $quick_login_send_time = Model_Api_V2_Common::cache('get', $send_time_key);
            $userType =$params['is_email'];
            if (!DB::select('id')
                ->from($userType == 'email' ? 'email_msg' : 'sms_msg')
                ->where('msgtype', '=',$messageType)
                ->and_where('isopen', '=', 1)
                ->execute()->current())
            {
                throw new Exception(sprintf('站点未开启%s验证', $userType == 'email' ? '邮件' : '短信'));
            }

            if ($quick_login_send_time) {
                $send_time = (int)$quick_login_send_time;
                //频繁发送检查
                if ((time() - $send_time) <= 120) {
                    $data = array(
                        'msg' => __("error_send_quick_msgcode"),
                        'status' => false,
                        "data" => array('type' => 1)
                    );
                    throw new Exception(__("error_send_quick_msgcode"));
                }
            }

            $send_key = "{$prefix}_{$user}";
            $send_code_key = "{$prefix}_code_" . $user;
            Model_Api_V2_Common::cache('set', $send_time_key, time());
            if (!$userType || $userType != 'email') {
                $status = json_decode(St_SMSService::send_member_msg($user, $messageType, "", "", $code), true);
            } else {
                $title = $GLOBALS['cfg_webname'] . '邮箱验证码';
                $content = '邮件验证码' . $code;
                $tstatus = St_EmailService::send_email($user, $title, $content);
                if ($tstatus) {
                    $status['Success'] = true;
                } else {
                    $status['Success'] = false;
                    $status['Message'] = '发送失败';
                }
            }
            if ($status['Success']) {
                Model_Api_V2_Common::cache('set', $send_key, 1);
                Model_Api_V2_Common::cache('set', $send_code_key, $code);
                $data['status'] = true;
                $data['msg'] = "发送成功";
            } else {
                $data['status'] = false;
                $data['msg'] = $status['Message'];
            }

        } catch (Exception $e) {
            $data['status'] = false;
            $data['msg'] = $e->getMessage();
        }
        return $data;

    }


}